<template>
  <view class="container">
    <FilterNavbar>
      <template #center>
        <view class="navbar-title"> {{ pageTitle }} </view>
      </template>
    </FilterNavbar>
    <!-- 违章车辆提示 -->
    <template v-if="waitViolationFlag">
      <ve-alert> 当前车辆存在待处理的违章订单，年检前请尽快处理违章 </ve-alert>
      <ve-gap size="24"></ve-gap>
    </template>
    <ve-form ref="formRef" :model="form" :rules="rules">
      <!-- 情况1：未带入车辆，需要手动选择 -->
      <ve-card title="车辆基本信息" type="none" fold v-model:initFold="foldStatus.fold1" v-if="pageFrom == 'indexTool'">
        <ve-form-item label="车牌号" :borderBottom="false" prop="licenseNo" required>
          <remote-select type="licenseNo" :label="form.licenseNo" @change="changeLicenseNo" v-model="form.carId" allowClear />
        </ve-form-item>
        <car-info-shadow v-if="carInfo.licenseNo" :info="carInfo" />
        <view :style="carInfo.licenseNo ? 'height: 24rpx;' : ''"></view>
      </ve-card>
      <!-- 情况2：带入年检id|车辆id|订单id，无需手动选择 -->
      <car-info :info="carInfo" v-else>
        <ve-cell label="年检单号" v-if="carInfo.inspectionNo">{{ carInfo.inspectionNo || '-' }}</ve-cell>
      </car-info>

      <ve-card title="年检信息" type="none" fold v-model:initFold="foldStatus.fold2">
        <ve-form-item label="年检证" labelPosition="top" prop="inspectionFileId">
          <view>
            <ve-upload v-model="form.inspectionFileId" single max-count="1"></ve-upload>
            <OcrButton v-if="form.inspectionFileId" ocrType="inspection" :fileId="form.inspectionFileId" @success="inspectionOCR_Ok" />
          </view>
        </ve-form-item>
        <ve-form-item label="年检单关联门店" prop="siteId" required>
          <remote-select type="site" v-model="form.siteId" v-model:label="form.siteName" :params="{ oldId: form.siteId }" allowClear />
        </ve-form-item>

        <ve-form-item label="本次年检日期" prop="inspectionTime">
          <ve-date-picker v-model="form.inspectionTime" mode="date" title="时间" @confirm="setPlanTime" allowClear></ve-date-picker>
        </ve-form-item>
        <ve-form-item label="年检间隔时间" unit="天" prop="inspectionLimitDay" labelTooltipContent>
          <template #content>
            <view>用于计算下次年检日期，年检有效期至</view>
            =本次年检日期+年检间隔时间。
          </template>
          <ve-input-number v-model="form.inspectionLimitDay" :precision="0" :min="0" @change="setPlanTime" />
        </ve-form-item>
        <ve-form-item label="年检有效期至" prop="planTime">
          <ve-date-picker v-model="form.planTime" mode="date" allowClear />
        </ve-form-item>

        <ve-form-item label="年检厂" prop="locationId">
          <remote-select
            v-model="form.locationId"
            v-model:label="form.location"
            :params="{
              idList: [form.locationId],
            }"
            allowClear
            type="supplierInspect"
          />
        </ve-form-item>

        <ve-form-item label="承租人信息">
          <remote-select
            v-model="form.memberId"
            :label="memberLabel"
            :disabled="byOrder"
            :params="{
              oldId: form.memberId,
              carId: form.carId,
              orderTypeList: [3], // 仅关联长租
            }"
            allowClear
            type="member_order_list"
            @change="memberChange"
          ></remote-select>
        </ve-form-item>

        <ve-form-item label="关联订单号">
          <remote-select
            v-model="form.businessOrderId"
            :label="form.orderNo"
            :disabled="byOrder"
            :params="{
              carId: form.carId,
              memberId: form.memberId,
              orderTypeList: [3], // 仅关联长租
              oldOrderType: form.orderType,
              oldOrderId: form.businessOrderId,
              useAuth: 1,
            }"
            type="orderCar"
            allowClear
            @change="orderChange"
          />
        </ve-form-item>

        <ve-form-item label="负责人" prop="undertakerId'">
          <remote-select
            v-model="form.undertakerId"
            :label="form.undertaker"
            :params="{ oldId: form.undertakerId, siteIdList: [carInfo.siteId] }"
            type="staff_all_bysite"
            allowClear
            @change="changeUndertaker"
          />
        </ve-form-item>

        <ve-form-item label="备注" labelPosition="top">
          <ve-input v-model="form.remark" maxlength="200" type="textarea" />
        </ve-form-item>
        <ve-form-item label="上传照片" labelPosition="top" :borderBottom="false" prop="fileIdList">
          <ve-upload v-model="form.fileIdList" maxCount="30"></ve-upload>
        </ve-form-item>
      </ve-card>

      <ve-card title="年检费用" type="none" fold v-model:initFold="foldStatus.fold3">
        <ve-form-item label="年检费" unit="元">
          <template #label-extra>
            <ve-tag v-if="assetFeeInfo.feeStatus == 1" title="已付款无法编辑" color="orange" />
          </template>
          <ve-input-number
            v-model="form.inspectionAmount"
            :precision="2"
            :min="0"
            :max="99999999.99"
            :disabled="assetFeeInfo.feeStatus == 1"
          />
        </ve-form-item>
        <ve-form-item label="费用备注" :borderBottom="false" labelPosition="top">
          <ve-input v-model="form.feeRemark" maxlength="200" type="textarea" />
        </ve-form-item>
      </ve-card>
      <ve-bottom-box size="mini">
        <ve-button type="primary" size="long" :loading="saveLoading" @click="handleSave">确认</ve-button>
      </ve-bottom-box>
    </ve-form>
  </view>
</template>

<script setup>
  import dayjs from 'dayjs'
  import { ref, computed } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { userStore } from '@/stores'
  import useFormFold from '@/hooks/useFormFold'
  import FilterNavbar from '@/components/FilterNavbar'
  import OcrButton from '@/components/ocr-button.vue'
  import { useLoadDataAndHotUpdateNavigateBack } from '@/hooks/useListNavigate'
  import { addOrEditCarInspect, getInspectDetail, getCarViolationAPI } from '@/api/asset/car-inspect'
  import { getWarnConfig } from '@/api/dict/operate'
  import { findOrder } from '@/api/asset/car-violation'
  import { getCarDetail, orderCarInfo } from '@/api/asset/car-manager'
  import useToast from '@/hooks/useToast'
  import CarInfo from '@/pages/common/components/car-info.vue'
  import CarInfoShadow from '@/pages/common/components/car-info-shadow.vue'

  const userInfoStore = userStore()

  const { foldStatus, foldValidate } = useFormFold([
    {
      key: 'fold1',
      props: ['licenseNo'],
    },
    {
      key: 'fold2',
      props: ['siteId'],
    },
    {
      key: 'fold3',
    },
  ])

  const form = ref({})
  const rules = {
    licenseNo: {
      required: true,
      message: '请选择车牌号',
    },
    siteId: {
      required: true,
      message: '请选择年检单关联门店',
    },
  }
  const formRef = ref(null)
  const saveLoading = ref(false)
  const handleSave = (validateInspect = true) => {
    // 表单验证
    formRef.value.validate((valid, errors) => {
      if (valid) {
        // 校验年检时间
        if (validateInspect && validateInspectTimeFn() == false) return
        saveLoading.value = true
        const params = {
          ...form.value,
          // 补齐时分秒
        }
        if (form.value.inspectionTime) {
          params.inspectionTime = dayjs(form.value.inspectionTime).format('YYYY-MM-DD 00:00:00')
        }
        addOrEditCarInspect(params)
          .then((res) => {
            saveLoading.value = false
            if (res.code == 200) {
              useToast({
                title: '操作成功',
              }).then(() => {
                // 车辆管理列表增加年检成功后，跳转至年检列表
                if (pageFrom.value == 'carManagerList') {
                  uni.redirectTo({
                    url: `/pages/asset/car-inspect/list?id=${carInfo.value.id}`,
                  })
                }
                // 常用工具增加年检成功后，跳转至年检列表
                else if (pageFrom.value == 'indexTool') {
                  // 先跳转到车辆详情页
                  uni.redirectTo({
                    url: `/pages/asset/car-manager/detail/index?id=${carInfo.value.id}`,
                    success() {
                      // 再跳转到车辆详情>保养列表页
                      uni.navigateTo({
                        url: `/pages/asset/car-inspect/list?id=${carInfo.value.id}`,
                      })
                    },
                  })
                } else {
                  uni.navigateBack()
                }
                // 触发事件，车辆编辑-年检新增成功
                uni.$emit('carEdit_inspectAddOk', params)
                // 刷新list
                uni.$emit('carInspect_getList')
              })
            } else {
              uni.showToast({
                title: res.message,
                icon: 'none',
              })
            }
          })
          .catch(() => {
            saveLoading.value = false
          })
      } else {
        saveLoading.value = false
        foldValidate(errors)
        console.log('验证失败', errors)
      }
    })
  }

  // 选择车牌号
  const changeLicenseNo = (carId, option = {}) => {
    form.value.carId = carId
    form.value.licenseNo = option.licenseNo
    form.value.siteId = option.siteId
    form.value.siteName = option.siteName
    carInfo.value = option

    // 清空承租人信息和关联订单号信息
    form.value.memberId = undefined
    form.value.memberName = undefined
    form.value.memberPhone = undefined
    form.value.businessOrderId = undefined
    form.value.orderNo = undefined
    form.value.orderType = undefined

    // 清空违章信息
    waitViolationFlag.value = false

    // 获取车辆违章以及关联订单信息
    if (carId) {
      getCarViolation(carId)
      selectLinkedOrder()
    }
  }

  // 校验年检时间，给出提示
  const validateInspectTimeFn = () => {
    // 编辑不校验
    if (form.value.id) return true
    const tip = '新增年检的有效期早于车辆上的年检有效期，请确认是否新增？'

    // 获取当前车辆的下次年检日期
    const currentPlanTime = carInfo.value.planTime
    // 获取新增的年检日期
    const newPlanTime = form.value.planTime

    // 检查日期是否有效
    if (currentPlanTime && newPlanTime) {
      const currentPlanDate = dayjs(currentPlanTime)
      const newPlanDate = dayjs(newPlanTime)

      // 比较日期
      if (newPlanDate.isBefore(currentPlanDate)) {
        uni.showModal({
          title: '提示',
          cancelText: '取消',
          confirmText: '确认',
          content: tip,
          success: (res) => {
            if (res.confirm) {
              handleSave(false)
            }
          },
        })
        return false
      }
    }

    // 如果日期合理或未设置日期，则返回 true
    return true
  }

  const setPlanTime = () => {
    if (form.value.inspectionTime && form.value.inspectionLimitDay != undefined) {
      form.value.planTime = dayjs(form.value.inspectionTime).add(form.value.inspectionLimitDay, 'day').format('YYYY-MM-DD')
    }
  }

  // 选择负责人
  const changeUndertaker = (a, option = {}) => {
    form.value.undertakerId = a
    form.value.undertaker = option.realname
  }

  // 承租人label
  const memberLabel = computed(() => {
    if (form.value.memberName || form.value.memberPhone) {
      return [form.value.memberName, form.value.memberPhone].join(' | ')
    } else {
      return ''
    }
  })
  // 承租人change
  const memberChange = (val, option) => {
    if (val) {
      form.value.memberId = val
      form.value.memberName = option.memberName
      form.value.memberPhone = option.phone

      // 需要获取最新的车牌号信息
      selectLinkedOrder()
    } else {
      form.value.memberId = undefined
      form.value.memberName = undefined
      form.value.memberPhone = undefined
    }
  }

  // 选择长租的关联订单
  const selectLinkedOrder = () => {
    findOrder({
      carId: form.value.carId,
      memberId: form.value.memberId,
      orderTypeList: [3], // 仅关联长租
      useAuth: 1,
    }).then((res) => {
      if (res.code == 200) {
        const orderList = res.result
        if (orderList.length > 0) {
          // 当前存在已选择的订单时，判断是否需要清空
          let defaultSelectFirst = true
          if (form.value.businessOrderId) {
            const hasSameOrderId = orderList.some((item) => item.orderId == form.value.businessOrderId)
            if (hasSameOrderId) {
              // 存在相同订单，则不再默认选中第一个
              defaultSelectFirst = false
            }
          }
          const order = orderList[0]
          if (defaultSelectFirst) {
            form.value.orderId = order.orderId
            form.value.businessOrderId = order.orderId
            form.value.orderNo = order.orderNo
            form.value.memberId = order.memberId
            form.value.memberPhone = order.memberPhone
            form.value.memberName = order.memberName
          } else {
            form.value.orderId = order.orderId
            form.value.businessOrderId = order.orderId
            form.value.orderNo = order.orderNo
          }
        }
      }
    })
  }

  // 订单change
  const orderChange = (val, option) => {
    if (val) {
      form.value.orderNo = option.orderNo
      form.value.orderType = option.orderType
      // 更新承租人信息
      form.value.memberId = option.memberId
      form.value.memberPhone = option.memberPhone
      form.value.memberName = option.memberName
    } else {
      form.value.orderNo = undefined
      form.value.orderType = undefined
    }
  }

  const inspectionOCR_Ok = (res) => {
    if (res?.date) {
      useToast({
        title: '读取成功',
      })
      form.value.planTime = dayjs(res.date).endOf('month').format('YYYY-MM-DD')
    }
  }

  const carInfo = ref({})
  const assetFeeInfo = ref({})
  const getDetail = async (id) => {
    getInspectDetail({ id: id }).then((res) => {
      carInfo.value = res.result
      assetFeeInfo.value = res.result.assetFeeInfo || {}
      form.value = {
        // 年检基本信息
        id: res.result.id,
        carId: res.result.carId,
        licenseNo: res.result.licenseNo,
        siteId: res.result.siteId,
        siteName: res.result.siteName,
        planTime: res.result.planTime,
        locationId: res.result.locationId,
        location: res.result.location,
        inspectionFileId: res.result.inspectionFileId,
        inspectionTime: res.result.inspectionTime,
        // 承租人
        memberId: res.result.memberId,
        memberName: res.result.memberName,
        memberPhone: res.result.memberPhone,
        // 关联订单
        businessOrderId: res.result.businessOrderId,
        orderNo: res.result.orderNo,
        orderType: res.result.orderType,
        // 负责人
        undertakerId: res.result.undertakerId,
        undertaker: res.result.undertaker,
        remark: res.result.remark,
        fileIdList: res.result.fileIdList,
        // 年检费用
        inspectionAmount: res.result.inspectionAmount,
        feeRemark: res.result.feeRemark,
        // 年检间隔时间（代办事项配置，不参与保存）
        inspectionLimitDay: inspectionLimitDay.value,
      }
    })
  }

  // 获取车辆信息
  const getCarDetailApi = (id) => {
    getCarDetail({ id: id }).then((res) => {
      carInfo.value = res.result
      form.value = {
        carId: res.result.id,
        licenseNo: res.result.licenseNo,
        siteId: res.result.siteId,
        siteName: res.result.siteName,
        // 负责人默认登录人
        undertakerId: userInfoStore.staffInfo.staffId,
        undertaker: userInfoStore.staffInfo.realname,
        // 年检间隔时间（代办事项配置，不参与保存）
        inspectionLimitDay: inspectionLimitDay.value,
      }

      // 需要关联订单
      selectLinkedOrder()
    })
  }

  // 获取订单的车辆信息
  const getOrderCarDetail = (id) => {
    orderCarInfo({ id: id, type: 3 }).then((res) => {
      carInfo.value = res.result
      carInfo.value = res.result
      form.value = {
        carId: res.result.carId,
        licenseNo: res.result.licenseNo,
        siteId: res.result.siteId,
        siteName: res.result.siteName,
        // 订单信息
        businessOrderId: res.result.orderId,
        orderNo: res.result.orderCode,
        orderType: 3, // 长租
        memberId: res.result.memberId,
        memberName: res.result.memberName,
        memberPhone: res.result.memberPhone,
        // 负责人默认登录人
        undertakerId: userInfoStore.staffInfo.staffId,
        undertaker: userInfoStore.staffInfo.realname,
        // 年检间隔时间（代办事项配置，不参与保存）
        inspectionLimitDay: inspectionLimitDay.value,
      }
      // 获取违章信息
      getCarViolation(form.value.carId)
    })
  }

  // 获取车辆违章信息
  const waitViolationFlag = ref(false)

  // 违章相关
  const getCarViolation = (id) => {
    // 获取未处理的list
    getCarViolationAPI({ carId: id, eventStatus: 0, pageSize: 10, pageNumber: 1 }).then((res) => {
      if (res.result.data.length) {
        waitViolationFlag.value = true
      }
    })
  }

  const pageTitle = ref('新增年检')
  const byOrder = ref(false)
  const inspectionLimitDay = ref(0)
  const pageFrom = ref('')
  // 初始化表单和配置
  const initFormAndConfig = (options) => {
    const { id, orderId, carId, from } = options
    pageFrom.value = from
    getWarnConfig({ type: 1 }).then((res) => {
      inspectionLimitDay.value = res.result.inspectionLimitDay
      // 编辑
      if (id) {
        pageTitle.value = '编辑年检'
        getDetail(id)
      }
      // 从订单新增
      if (orderId) {
        byOrder.value = true
        getOrderCarDetail(orderId)
        return
      }
      // 从车辆新增
      if (carId) {
        getCarDetailApi(carId)
        getCarViolation(carId)
        return
      }
      // 未带入任何信息
      form.value = {
        // 负责人默认登录人
        undertakerId: userInfoStore.staffInfo.staffId,
        undertaker: userInfoStore.staffInfo.realname,
        // 年检间隔时间（代办事项配置，不参与保存）
        inspectionLimitDay: inspectionLimitDay.value,
      }
    })
  }

  onLoad((options) => {
    initFormAndConfig(options)
  })
</script>

<style lang="scss" scoped>
  page {
    background: #f7f8fa;
  }
  .container {
    height: auto;
    padding: 24rpx 24rpx;
    background: #f7f8fa;
  }
  :deep(.ve-textarea) {
    background: #eff0f2;
  }
</style>
